package cn.wind.xboot.module.web.controller;

import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.upload.OssUpload;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 阿里云oss上传文件接口
 *
 * @author WangHao
 * @date 2019-02-18
 */
@Slf4j
@Controller
@Api(value ="myUpload",tags = "文件上传接口")
@RequestMapping("/myUpload")
public class MyUploadController {

    /**
     * 单个上传文件
     * @param file
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadOne")
    @ResponseBody
    public ApiResult uploadFile(MultipartFile file, String code) throws Exception {
        Map<String,String> map = Maps.newHashMap();
        if (file!=null && !file.isEmpty()){
            map.put("fileName",file.getOriginalFilename());
            map.put("filePath",OssUpload.uploadFile(file,code));
        }else {
            return ApiResult.Custom().failure( 900420,"文件为空!" );
        }
        return ApiResult.Custom().success("文件上传成功").add( map );
    }

    /**
     * 同时上传多个文件
     * @param file
     * @param httpServletResponse
     * @param code 阿里云oss中的文件夹,根据所传的参数自动创建
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadBatch")
    @ResponseBody
    public ApiResult uploadBatch(MultipartFile[] file, HttpServletResponse httpServletResponse, String code) throws Exception {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
       List<String> listImagePath = new ArrayList<>();
       for (MultipartFile mf : file) {
            if (!mf.isEmpty()) {
                listImagePath.add(OssUpload.uploadFile(mf, code));
           }
        }
       return ApiResult.Custom().success().add( StringUtils.join(listImagePath, ","));
   }
}
